/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : course.js                                 
*  Description  : 코스공략 리스트 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-04-27  김효순    Created.  
*  2012-04-30  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 상단 타이틀
	function clsCourseTitle()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsCourseTitle.prototype = {
		_init: function(){
			var $layer = $("div#container>section#main_content>div.golf_board article.depth2_tab");
			
			this._HTMLDom = {
				"$layer": $layer
				, "$tabs": $layer.find("li")
			}
			
			$layer.data("idx", null); // 인덱스로 관리
			
			this.display();
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setIdx: function(val){
			var $layer = this.$getLayer();
			
			if(val == $layer.data("idx")) return false;
			
			$layer.data("idx", val);
			
			this.display();
			return true;
		}
		, getIdx: function(){
			return this.$getLayer().data("idx");
		}
		, display: function(){
			var $layer = this.$getLayer(), $tabs = this._HTMLDom["$tabs"];
			var idx = $layer.data("idx");
			
			// 현재 인덱싱된 타이틀만 on설정
			$tabs.find("img").each(function(n){
				var imgSrc = $(this).attr("src");
				var szImgName = imgSrc.replace(/(.*)\/(.*).gif/g, function(){
					return arguments[1] + "/" + arguments[2].replace("_on", "");
				});
				
				$(this).attr("src", szImgName + ((idx == n) ? "_on":"") + ".gif");
			});
		}
	}
	
	// 검색
	function clsSearch()
	{
		this._HTMLDom = null;
		this.idx = null;
		this._ERRMSG = {
			"_NOVALUE": "검색어를 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsSearch.prototype = {
		_init: function(){
			var $layer = $("div#container>section#main_content>div.golf_board>article.golf_board_search");
			var thisClass = this;
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setIdx(0);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setIdx: function(idx){
			var $layer = this.$getLayer();
			
			this.idx = idx;
			$layer.find("div.selectlayer>ul").hide();
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			
			var szText = $layer.find("li:eq(" + this.idx + ") a").text();
			
			$layer.find("p.default:first a").html(szText);
		}
		, getIdx: function(){
			return this.idx;
		}
		, getValue: function(){
			return this.$getLayer().find(":text").val();
		}
		, isValid: function(){
			var $layer = this.$getLayer();
			var val = this.getValue();
			this.errMsg = null;
			
			if(!val){
				this.errMsg = "_NOVALUE";
				return false;
			}
			
			return true;
		}
		, focus: function(){
			this.$getLayer().find(":text").trigger("focus");
		}
		, getError: function(){
			if(!this.errMsg) return null;
			else return this._ERRMSG[this.errMsg];
		}
		, toggle: function(){
			this.$getLayer().find("div.selectlayer>ul").toggle("fast");
		}
	}
	
	// 코스 리스트
	function clsCourseList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsCourseList.prototype = {
		_init: function(){
			$layer = $("div#container>section#main_content>div.golf_board>article.board_list");
			$layer.find("tbody tr:first td:eq(3) span img").error(function(){
				$(this).attr("src", _gf.getDefaultProfileImage());
			});
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
				, "$noresult": $layer.prev("article.board_list_none")
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, setWriterInfo: function(key, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["키"]+"" == key+"") break;
			}
			
			if(i<this.listData.length){
				this.listData[i]["작성자"] = thisData;
				this.displayWriter(i);
			}
		}
		, setNiceShotList: function(courseKey, thisData){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["키"]+"" == courseKey+"") break;
			}
			
			if(i<this.listData.length){
				this.listData[i]["나이스샷"] = thisData;
				this.displayNoceShot(i);
			}
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var $noresult = this._HTMLDom["$noresult"];
			var thisClass = this;
			
			if(this.listData.length){
				$layer.show();
				$noresult.hide();
				
				$layer.find("tbody").empty();
				for(var i=0;i<this.listData.length;i++){
					$layer.find("tbody").append($element.clone(true));
				}
				$layer.find("tbody tr").each(function(n){
					$(this).find("td:eq(0)").html(thisClass.listData[n]["넘버"]);
					$(this).find("td.tit_g").html(thisClass.listData[n]["골프장코스명"] + "<span class='ff_normal'>" + thisClass.listData[n]["홀명"] + "H</span>");
					$(this).find("td:eq(2) a").html(thisClass.listData[n]["제목"]);
					$(this).find("td:eq(2) span").html("(" + thisClass.listData[n]["댓글수"] + ")");
					$(this).find("td:eq(3) span img").attr("src", _gf.getDefaultProfileImage());
					$(this).find("td:eq(3) span.nickname").html(thisClass.listData[n]["작성자"]["닉네임"]);
					$(this).find("td:eq(4)").html(thisClass.listData[n]["작성일"]);
					$(this).find("td:eq(5)").html(thisClass.listData[n]["조회수"]);
					
					$tmp = $(this).find("td:eq(6)").children().clone(true);
					$(this).find("td:eq(6)").html("0").prepend($tmp);;
				});
			}else{
				$layer.hide();
				$noresult.show();
			}
		}
		, displayNoceShot: function(n){
			var $layer = this.$getLayer();
			var thisClass = this;
			var $obj = $layer.find("tbody tr").eq(n);
			var d = this.listData[n]["나이스샷"];
			
			$tmp = $obj.find("td:eq(6)").children().clone(true);
			$obj.find("td:eq(6)").html(d.length).prepend($tmp).hover(function(){
				if(d.length) _gf.showMemberLayer($(this), d, "right", -115, $(this).height());
			}, function(){
				_gf.closeMemberLayer();
			});
		}
		, displayWriter: function(n){
			var $layer = this.$getLayer();
			var thisClass = this;
			var $obj = $layer.find("tbody tr").eq(n);
			
			$obj.find("td:eq(3) span img").attr("src", _gf.filePath2Url(this.listData[n]["작성자"]["이미지"])).hover(function(){
				_gf.showProfileLayer($(this), thisClass.listData[n]["작성자"], "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
			$obj.find("td:eq(3) span.nickname").html(this.listData[n]["작성자"]["닉네임"]).hover(function(){
				_gf.showProfileLayer($(this), thisClass.listData[n]["작성자"], "left", 0, $(this).height());
			}, function(){
				_gf.closeProfileLayer();
			});
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			var $noresult = this._HTMLDom["$noresult"]
			
			$layer.hide();
			$noresult.hide();
			
			if($layer.next("div#tmpSpin").length == 0){
				$layer.after("<div id='tmpSpin' style='position:relative; width:650px; height:100px;'></div>");
			}
			$layer.next("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.next("div#tmpSpin").spin(false).hide();
			$layer.show();
		}
		, getCourseKey: function(n){
			return this.listData[n]["키"];
		}
	}
	
	// 공지사항
	function clsNotice()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsNotice.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content div.golf_board >dl.golf_board_note");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setInfo({});
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("dd").empty();
			if(this.infoData["공지키"]) $layer.find("dd").html(this.infoData["제목"]);
		}
	}
	
	function clsComm()
	{
		this.courseList = null;
		this.courseRequest = null;
		this.coursePageData = null;
		// 공지
		this.noticeInfo = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.courseRequest = {};
		}
		, setCourseRequest: function(key, val){
			if(typeof key == "object") this.courseRequest = key;
			else this.courseRequest[key] = val;
		}
		, getCourseRequest: function(){
			return this.courseRequest;
		}
		, getCourseList: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = (this.courseRequest["내꺼"]) ? "getKnowhowBoardMyList":"getKnowhowBoardList";
			var curPage = this.courseRequest["페이지"];
			
			var objVars = {
				"제목": ""
				, "골프장코드": ""
				, "골프장명": ""
				, "내용": ""
				, "작성자": ""
			}
			switch(this.courseRequest["검색종류"]){
				case 0:
					for(var k in objVars){
						objVars[k] = this.courseRequest["검색어"]
					}
					break;
				case 1:
					objVars["제목"] = this.courseRequest["검색어"]
					break;
				case 2:
					objVars["작성자"] = this.courseRequest["검색어"]
					break;
				case 3:
					objVars["골프장코드"] = this.courseRequest["검색어"]
					objVars["골프장명"] = this.courseRequest["검색어"]
					break;
			}
			
			var options = {
				"title": objVars["제목"]
				, "golfclub_id": objVars["골프장코드"]
				, "golfclub_name": objVars["골프장명"]
				, "content": objVars["내용"]
				, "reg_nickname": objVars["작성자"]
			}
			
			document.objGlobal.ajax({
				"sid": "KB001",
				"servicename": serviceName,
				"listcount": this.courseRequest["페이지당수"],
				"currpageno": curPage
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						var no = res["전체수"] - (curPage-1)*thisClass.courseRequest["페이지당수"];
						var reg_date = _util.nvl(obj["reg__date"])+"";
						
						var golfCourseName = "";
						var hole = "";
						if(_util.nvl(obj["golfclub__seq"])){
							golfCourseName = _util.nvl(obj["golfclub__name"]) + " " + _util.nvl(obj["course__info__name"]);
							hole = _util.nvl(obj["hole__no"]);
						}else{
							golfCourseName = _util.nvl(obj["golfclub__data"]) + " " + _util.nvl(obj["course__data"]);
							hole = _util.nvl(obj["hole__data"]);
						}
						
						res["결과값"].push({
							"키": _util.nvl(obj["board__seq"])
							, "넘버": no-i
							, "골프장코드": _util.nvl(obj["golfclub__seq"])
							, "골프장코스명": golfCourseName
							, "홀명": hole
							, "제목": _util.nvl(obj["title"])
							, "댓글수": _util.nvl(obj["cr__cnt"])
							, "작성자": {
								"아이디": _util.nvl(obj["reg__id"])
								, "닉네임": _util.nvl(obj["reg__nickname"])
								, "이미지": _gf.filePath2Url(_util.nvl(obj["user__image"]))
							}
							, "작성일": reg_date.substrEx(0,4) + "-" + reg_date.substrEx(4, 2) + "-" + reg_date.substrEx(6,2)
							, "조회수": _util.nvl(obj["hit"])
							, "내꺼": _util.nvl(obj["my__article__yn"])
						});
					}
				}
				
				document.objControl.finishCourseList(res);
			});
		}
		, getCourseData: function(){
			return this.courseList;
		}
		, getCoursePageData: function(){
			return this.coursePageData;
		}
		, getNoticeInfo: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getBookingBoardList";
			
			var serviceName = "getKnowhowBoardList";
			
			document.objGlobal.ajax({
				"sid": "KB001",
				"servicename": serviceName,
				"listcount": 1,
				"currpageno": 1
			}, {
				"title": ""
				, "golfclub_id": ""
				, "golfclub_name": ""
				, "content": ""
				, "reg_nickname": ""
				, "notice_yn": "Y"
			}, function(ret){
				if(ret["msp"]["contents"]["serviceResult"] == "00000"){
					thisClass.noticeInfo = {};
					
					if(ret["msp"]["contents"]["items"]){
						var obj = ret["msp"]["contents"]["items"];
						
						thisClass.noticeInfo = {
							"공지키": obj["title"]
							, "제목": obj["content"]
						}
					}
				}else{
					thisClass.bookingList = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "메시지": document.objGlobal.getResultMsg(ret)
					}
				}
				
				document.objControl.finishNoticeInfo();
			});
		}
		, getNoticeData: function(){
			return this.noticeInfo;
		}
		// 나이스샷
		, getNiceShotList: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "getKnowhowBoardNiceshot";
			var options = {
				"board_seq": arg["코스공략코드"]
			}
			_gf.ajax({
				"sid": "KB001"
				, "servicename": serviceName
				, "listcount": 10000
				, "currpageno": 1
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "코스공략코드": arg["코스공략코드"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						res["결과값"].push({
							"아이디": _util.nvl(obj["reg__id"])
							, "닉네임": _util.nvl(obj["reg_nickname"])
							, "이미지": _gf.filePath2Url(_util.nvl(obj["user_image"]))
						});
					}
				}
				
				document.objControl.finishNiceShotList(res);
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objCourseTitle = null;
		this.objCourseList = null;
		this.objCoursePage = null;
		this.objSearch = null;
		this.objNotice = null;
		
		this.ynMy = _util.getParam("q_my");
		
		this._permitStart = null;
		
		
		this._init();
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objCourseTitle = new clsCourseTitle();
			this.objCourseList = new clsCourseList();
			this.objCoursePage = new _gf.clsPaging($("#idCourseListPage"), 10, 10);
			this.objSearch = new clsSearch();
			this.objNotice = new clsNotice();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 전체게시글, 내가쓴글
			this.objCourseTitle.$getLayer().on("click", "li", function(){
				var idx = thisClass.objCourseTitle.$getLayer().find("li").index($(this));
				
				// 로그인 체크
				if(idx == 1 && !_util.getCookie("member_id")){
					if(!confirm(_LOGIN_TEXT)) return;
					_gf.goLogin();
					return;
				}
				
				document.location.href = document.location.pathname + ((idx) ? "?q_my=Y":"");
			});
			
			// 검색 바인드
			this.objSearch.$getLayer().on("click", "div.selectlayer>p:first, li, input:image", function(){
				switch($(this).get(0).tagName.toUpperCase()){
					// 검색타입
					case "P": 
						thisClass.objSearch.toggle();
						break;
					// 검색타입 선택
					case "LI": 
						var n = thisClass.objSearch.$getLayer().find("li").index($(this));
						thisClass.objSearch.setIdx(n);
						break;
					// 검색
					case "INPUT":
						if(!thisClass.objSearch.isValid()){
							alert(thisClass.objSearch.getError());
							thisClass.objSearch.focus();
							return;
						}
						
						thisClass.objCoursePage.setPage(1);
						
						thisClass.requestCourseList();
						break;
				}
				
				
			});
			
			// 검색
			this.objSearch.$getLayer().on("keydown", "input:text", function(e){
				e = e || event;
				
				if(e.keyCode == 13){
					thisClass.objSearch.$getLayer().find("input:image").trigger("click");
				}
			});
			
			// 리스트클릭
			this.objCourseList.$getLayer().on("click", "tbody tr", function(){
				var n = thisClass.objCourseList.$getLayer().find("tbody tr").index($(this));
				var courseKey = thisClass.objCourseList.getCourseKey(n);
				
				thisClass.goViewPage(courseKey);
			});
			
			// 페이지이동
			$(this.objCoursePage).bind("evtPageClick", function(){
				thisClass.requestCourseList();
			});
			
			// 글쓰기
			$("div#container section#main_content").on("click", "img[alt='글쓰기']", function(){
				thisClass.goWritePage();
			});
		}
		, _start: function(){
			var q_my = _util.getParam("q_my");
			var q_searchType = _util.getParam("q_searchType");
			var q_searchText = _util.getParam("q_searchText");
			var q_page = _util.getParam("q_page");
			
			// 로그인 체크
			if(this.q_my == "Y" && !_util.getCookie("member_id")){
				if(!confirm(_LOGIN_TEXT)) history.back();
				_gf.goLogin();
				return;
			}
			
			// 공지사항
			this.objComm.getNoticeInfo();
			
			// 전체게시글로 default 설정
			this.objCourseTitle.setIdx((q_my == "Y") ? 1:0);
			if(q_searchType) this.objSearch.setIdx(q_searchType-0);
			if(q_searchText) this.objSearch.setValue(q_searchText);
			if(q_page) this.objCoursePage.setPage(q_page);
			else this.objCoursePage.setPage(1);
			
			this.requestCourseList();
		}
		// 코스리스트 요청
		, requestCourseList: function(){
			this.objComm.setCourseRequest({
				"내꺼": Boolean(this.objCourseTitle.getIdx())
				, "검색종류": this.objSearch.getIdx()
				, "검색어": this.objSearch.getValue()
				, "페이지당수": this.objCoursePage.getCountPerPage()
				, "페이지": this.objCoursePage.getPage()
			});
			this.objCourseList.spinStart();
			this.objComm.getCourseList();
		}
		// 코스리스트 완료
		, finishCourseList: function(ret){
			var thisClass = this;
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objCourseList.spinEnd();
			this.objCourseList.setList(ret["결과값"]);
			
			this.objCoursePage.setTotalCount(ret["전체수"]);
			this.objCoursePage.display();
			
			for(var i=0;i<ret["결과값"].length;i++){
				_gf.getMemberInfo({
					"코스공략코드": ret["결과값"][i]["키"]
					, "아이디": ret["결과값"][i]["작성자"]["아이디"]
					, "콜백": function(res, info, arg){
						thisClass.objCourseList.setWriterInfo(arg["코스공략코드"], info);
					}
				});
				
				this.objComm.getNiceShotList({
					"코스공략코드": ret["결과값"][i]["키"]
				});
			}
		}
		// 공지사항 완료
		, finishNoticeInfo: function(){
			var thisData = this.objComm.getNoticeData();
			
			this.objNotice.setInfo(thisData);
		}
		// 나이스샷 완료
		, finishNiceShotList: function(ret){
			this.objCourseList.setNiceShotList(ret["코스공략코드"], ret["결과값"]);
		}
		, getParams: function(){
			var p = {
				"q_my": (this.objCourseTitle.getIdx() ? "Y":"")
				, "q_searchType": this.objSearch.getIdx()
				, "q_searchText": this.objSearch.getValue()
				, "q_page": this.objCoursePage.getPage()
			}
			
			return p;
		}
		// 상세보기 이동
		, goViewPage: function(q_seq){
			var p = this.getParams();
			p["q_seq"] = q_seq;
			
			document.location.href = _ROOT + "/course/course_view.html" + _util.object2paramString(p);
		}
		// 글쓰기 이동
		, goWritePage: function(){
			var p = this.getParams();
			
			document.location.href = _ROOT + "/course/course_write.html" + _util.object2paramString(p);
		}
	}
	
	document.objControl = new clsControl();
});